import type { FieldError } from '../interface/ValidateType';
/**
 *
 *
 * @export
 * @param {Promise<FieldError>[]} promiseList
 * @returns {Promise<FieldError[]>}
 */
export function allPromiseFinish(
  promiseList: Promise<FieldError>[],
): Promise<FieldError[]> {
  let hasError = false;
  let count = promiseList.length;
  const results: FieldError[] = [];

  if (!promiseList.length) {
    return Promise.resolve([]);
  }

  // 把所有Field的检测结果(Promise<FieldError>)合道一个promise中
  return new Promise((resolve, reject) => {
    promiseList.forEach((promise, index) => {
      promise
        .catch((e) => {
          // console.log('---allPromiseFinish--catch--e--:',e)
          hasError = true;
          return e; //===  return Promise.resolve(e); 链式调用立马执行.then(...)
        })
        .then((result) => {
          //验证通过
          count -= 1;
          results[index] = result;
          // console.log('---allPromiseFinish--then--result--')
          if (count > 0) {
            return;
          }

          if (hasError) {
            //只要有一个Field没有检测通过  return的是Promise.reject(e);
            reject(results);
          }
          resolve(results);
        });
    });
  });
}
